package com.itheima.aop;

import com.itheima.annotation.LimitOperate;
import com.itheima.common.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
@Component
@Aspect
public class LimitOPerateAspect {
    @Autowired
    private HttpServletRequest httpServletRequest;

    @Pointcut("@annotation(com.itheima.annotation.LimitOperate)")
    public void pt(){}

    @Before("pt()")
    public void limitOperate(JoinPoint joinPoint) {
        //获取登录的username
        String token = httpServletRequest.getHeader("Token");
        Claims claims = JwtUtils.parseJWT(token);
        String username = claims.get("username", String.class);
        if (!(!Objects.isNull(username) &&username.equals("jinyong"))){
            //如果username是金庸那么就放行用注解的方法，不是的话则无影响
            throw new RuntimeException("没有权限进行该操作");
        }
    }
}